/**
 * 获取角色列表
 */
import React from 'react';
import { getRolelist } from '@/services/organization';

const FIELD_MAP = { createTime: 'create_time', roleCount: 'role_count' };

// 转换为服务端需要的格式，如： create_time asc
const transformOrderBy = (orderBy = '') => {
    const [field = '', order = ''] = orderBy.split('_');
    if (field && order) {
        return `${FIELD_MAP[field]} ${order.split('end')[0]}`;
    }
    return '';
};

const useRole = query => {
    const [outData, setOutData] = React.useState([]);
    const [total, setTotal] = React.useState(0);
    const [loading, setLoading] = React.useState(true);

    const fetchData = async () => {
        setLoading(true);
        const { orderBy, reload, ...rest } = query;

        const { data = {}, code } = (await getRolelist({ ...rest, orderBy: transformOrderBy(orderBy) })) || {};

        if (code === 10000) {
            setOutData(data.rows);
            setTotal(data.total);
        }
        setLoading(false);
    };

    React.useEffect(() => {
        fetchData();
    }, [query]);

    return [loading, outData, total];
};

export default useRole;
